<template>
    <el-card shadow="hover" class="layer-card">
      <template #header>
        <div class="card-head">
          <div class="title">
            <el-tag size="small" type="primary" effect="plain">
              {{ typeName(local.nodeType) }}
            </el-tag>
            <span class="path-preview">{{ path }}</span>
          </div>
          <div class="ops" v-if="!creatingSystem">
            <el-button
              link size="small" type="danger"
              :disabled="disableRemove"
              @click="$emit('remove', index)"
            >删除</el-button>
          </div>
        </div>
      </template>
  
      <el-form :model="local" :rules="rules" ref="formRef" label-width="92px" class="layer-form">
        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="设备类型" prop="nodeType">
              <el-select-v2
                v-model="local.nodeType"
                :options="typeOptions"
                :disabled="creatingSystem"
                placeholder="请选择类型"
                clearable
                filterable
                @change="emitChange('nodeType')"
              />
            </el-form-item>
          </el-col>
  
          <el-col :span="8">
            <el-form-item label="设备编码" prop="code">
              <el-input v-model="local.code" placeholder="设备编码（唯一，必填）" @change="emitChange('code')" />
            </el-form-item>
          </el-col>
  
          <el-col :span="8">
            <el-form-item label="设备名称" prop="name">
              <el-input v-model="local.name" placeholder="请输入名称" @change="emitChange('name')" />
            </el-form-item>
          </el-col>
        </el-row>
  
        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="设备规格">
              <el-input v-model="local.specification" placeholder="例：DN80×DN50；Q=40m³/h；H=56m" @change="emitChange('specification')" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备型号">
              <el-input v-model="local.model" placeholder="例：ISG80-160A" @change="emitChange('model')" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备材质">
              <el-input v-model="local.material" placeholder="例：泵体304；叶轮CF8；轴封SiC" @change="emitChange('material')" />
            </el-form-item>
          </el-col>
        </el-row>
  
        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="设备功率">
              <el-input v-model="local.power" placeholder="例：15kW/380V/50Hz" @change="emitChange('power')" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="设备品牌">
              <el-input v-model="local.brand" placeholder="例：南方泵业" @change="emitChange('brand')" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="制造厂家">
              <el-input v-model="local.manufacturer" placeholder="例：浙江南方泵业股份有限公司" @change="emitChange('manufacturer')" />
            </el-form-item>
          </el-col>
        </el-row>
  
        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="备件名称">
              <el-select-v2
                v-model="local.spareIds"
                :options="spareListOptions"
                placeholder="可多选"
                multiple
                collapse-tags
                collapse-tags-tooltip
                filterable
                clearable
                style="width: 200px;"
                @change="emitChange('spareIds')"
              />
            </el-form-item>
          </el-col>
  
          <el-col :span="8">
            <el-form-item label="特种设备">
              <el-select v-model.number="local.isSpecial" placeholder="请选择类型" @change="emitChange('isSpecial')">
                <el-option label="是" :value="1" />
                <el-option label="否" :value="0" />
              </el-select>
            </el-form-item>
          </el-col>
  
          <el-col :span="8">
            <el-form-item label="归属部门" prop="deptId">
              <el-tree-select
                v-model="local.deptId"
                :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="请选择归属部门"
                check-strictly
                @change="emitChange('deptId')"
              />
            </el-form-item>
          </el-col>
        </el-row>
  
        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="设备状态" prop="status">
              <el-select v-model.number="local.status" placeholder="请选择设备状态" @change="emitChange('status')">
                <el-option
                  v-for="dict in assetNodeStatus"
                  :key="dict.value"
                  :label="dict.label"
                  :value="Number(dict.value)"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
  
        <el-form-item label="备注说明">
          <el-input v-model="local.remark" placeholder="可空" type="textarea" :rows="2" @change="emitChange('remark')" />
        </el-form-item>
      </el-form>
    </el-card>
  </template>
  
  <script setup>
  import { ref, watch, computed, defineExpose } from "vue";
  
  // Props
  const props = defineProps({
    /** v-model */
    modelValue: { type: Object, required: true },
    /** 当前卡片序号（用于删除/标识） */
    index: { type: Number, required: true },
    /** 标题右侧预览路径（父组件生成更合理） */
    path: { type: String, default: "" },
    /** 是否“创建系统”模式 */
    creatingSystem: { type: Boolean, default: false },
  
    /** 下拉：类型/备件/部门/状态字典 */
    typeOptions: { type: Array, default: () => [] },
    spareListOptions: { type: Array, default: () => [] },
    deptOptions: { type: Array, default: () => [] },
    assetNodeStatus: { type: Array, default: () => [] },
  
    /** 删除按钮禁用控制（父组件决定何时允许删） */
    disableRemove: { type: Boolean, default: false },
  
    /** 规则扩展（可选） */
    extraRules: { type: Object, default: () => ({}) },
  });
  
  const emit = defineEmits(["update:modelValue", "remove", "field-change"]);
  
  // 本地副本，保持与 v-model 同步
  const local = ref(structuredClone(props.modelValue || {}));
  watch(
    () => props.modelValue,
    (v) => (local.value = structuredClone(v || {})),
    { deep: true }
  );
  function emitChange(field) {
    emit("update:modelValue", structuredClone(local.value));
    emit("field-change", { index: props.index, field, value: local.value[field] });
  }
  
  // 简单规则（可被父组件补充/覆盖）
  const baseRules = {
    nodeType: [{ required: true, message: "请选择类型", trigger: "change" }],
    name: [{ required: true, message: "请输入名称", trigger: "blur" }],
    code: [{ required: true, message: "请输入编号", trigger: "blur" }],
    status: [{ required: true, message: "请选择状态", trigger: "change" }],
    // deptId 若你的业务要求必须为叶子，可仅在父层做 isLeaf 校验；此处保持非必填
  };
  const rules = computed(() => ({ ...baseRules, ...props.extraRules }));
  
  const formRef = ref();
  
  function validate() {
    return formRef.value?.validate?.();
  }
  function resetFields() {
    return formRef.value?.resetFields?.();
  }
  
  defineExpose({ validate, resetFields });
  
  // 工具：类型名
  const TYPE_LABELS = {
    SYSTEM: "系统",
    MACHINE: "母设备",
    MODULE: "子设备",
    COMPONENT: "部件",
    PART: "零件",
  };
  function typeName(code) {
    return TYPE_LABELS[code] || code || "未知";
  }
  </script>
  
  <style scoped>
  .layer-card { border-radius: 12px; }
  .card-head { display: flex; align-items: center; justify-content: space-between; }
  .card-head .title { display: flex; align-items: center; gap: 8px; font-weight: 500; }
  .path-preview { color: #909399; }
  .layer-form :deep(.el-input),
  .layer-form :deep(.el-select),
  .layer-form :deep(.el-input-number) { width: 100%; }
  </style>
  